package com.wx.tnsperson.response;

import com.wx.tnsperson.exception.FileException;
import com.wx.tnsperson.pojo.FileProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @Author:LLH
 * @Date:2020/7/25
 */

@Service
public class FileService {


    //文件在本地存储地址
    private final Path fileStorageLocation;

    @Autowired
    public FileService ( FileProperties fileProperties ) {
        this.fileStorageLocation = Paths.get ( fileProperties.getUploadDir()).toAbsolutePath ().normalize ();
        try {
            Files.createDirectories ( this.fileStorageLocation );
        } catch (IOException e) {
            throw new FileException ( "无法创建存储上传文件的目录",e );
        }
    }

    /**
     * 存储文件到系统
     * @param file
     * @return
     */
    public String storeFile( MultipartFile file ) {
        String fileName= StringUtils.cleanPath ( file.getOriginalFilename () );

        try {
            //检查文件名称是否包含无效字符
            if(fileName.contains ( ".." )){
                throw  new FileException ( "对不起!文件名包含无效的路径序列" +fileName);
            }

            //将文件复制到目标位置(用相同的名称替换现有文件)
            Path targetLocation=this.fileStorageLocation.resolve ( fileName );
            Files.copy ( file.getInputStream (),targetLocation,StandardCopyOption.REPLACE_EXISTING );
            return fileName;
        } catch (IOException e) {
            throw new FileException ( "无法存储文件" + fileName +"请重试",e );
        }
    }


    /**
     * 加载文件
     * @param fileName 文件名
     * @return 文件
     */
    public Resource loadFileAsResource( String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource (filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new FileException("未找到文件" + fileName);
            }
        } catch (MalformedURLException ex) {
            throw new FileException("未找到文件" + fileName, ex);
        }
    }
}
